<template>
	<view class="container">
		<view class="page-title">发布需求</view>
		
		<form @submit="onSubmit">
			<!-- 需求描述 -->
			<view class="input-group">
				<view class="input-label">需求描述 *</view>
				<textarea class="form-textarea" 
						  v-model="formData.description" 
						  placeholder="请详细描述您的面料需求，如：面料类型、颜色、规格等"
						  maxlength="500"></textarea>
			</view>
			
			<!-- 需求数量 -->
			<view class="input-group">
				<view class="input-label">需求数量 *</view>
				<view class="quantity-row">
					<input class="quantity-input" 
						   v-model.number="formData.quantity" 
						   type="number" 
						   placeholder="请输入数量" />
					<input class="unit-input" 
						   v-model="formData.quantityUnit" 
						   placeholder="单位(如:米/码/公斤)" />
				</view>
			</view>
			
			<!-- 联系人信息 -->
			<view class="input-group">
				<view class="input-label">联系人</view>
				<input class="form-input" 
					   v-model="formData.contactName" 
					   placeholder="请输入联系人姓名" />
			</view>
			
			<view class="input-group">
				<view class="input-label">联系电话</view>
				<input class="form-input" 
					   v-model="formData.contactPhone" 
					   placeholder="请输入联系电话" />
			</view>
			
			<!-- 图片上传 -->
			<view class="input-group">
				<view class="input-label">需求图片（最多3张）</view>
				<view class="image-upload">
					<view v-for="(image, index) in imageList" :key="index" class="image-item">
						<image class="uploaded-image" :src="image" mode="aspectFill"></image>
						<view class="delete-btn" @click="deleteImage(index)">×</view>
					</view>
					<view v-if="imageList.length < 3" class="upload-btn" @click="chooseImage">
						<text class="upload-text">+</text>
					</view>
				</view>
			</view>
			
			<!-- 提交按钮 -->
			<view class="btn-group">
				<button class="btn-primary submit-btn" @click="onSubmit">发布需求</button>
			</view>
		</form>
	</view>
</template>

<script>
import { api } from '../../utils/request.js';
import authStore from '../../store/auth.js';

export default {
	data() {
		return {
			// 表单数据
			formData: {
				description: '',
				quantity: '',
				quantityUnit: '',
				contactName: '',
				contactPhone: '',
				image1: '',
				image2: '',
				image3: ''
			},
			
			// 图片列表（本地路径）
			imageList: [],
			
			// 提交状态
			submitting: false
		}
	},
	
	onLoad() {
		// 发布需求页面：买家发布需求
		// 需要登录验证，接口：POST /api/demand/create
		this.checkAuth();
	},
	
	methods: {
		// 检查登录状态
		async checkAuth() {
			if (!authStore.isLoggedIn()) {
				try {
					await authStore.loginWithWeixin();
				} catch (error) {
					uni.showModal({
						title: '提示',
						content: '需要登录后才能发布需求',
						success: (res) => {
							if (res.confirm) {
								uni.switchTab({ url: '/pages/user/index' });
							}
						}
					});
				}
			}
		},
		
		// 选择图片
		chooseImage() {
			uni.chooseImage({
				count: 3 - this.imageList.length,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.imageList = this.imageList.concat(res.tempFilePaths);
					this.updateFormImages();
				},
				fail: (error) => {
					console.error('选择图片失败:', error);
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 删除图片
		deleteImage(index) {
			this.imageList.splice(index, 1);
			this.updateFormImages();
		},
		
		// 更新表单中的图片字段
		updateFormImages() {
			this.formData.image1 = this.imageList[0] || '';
			this.formData.image2 = this.imageList[1] || '';
			this.formData.image3 = this.imageList[2] || '';
		},
		
		// 表单验证
		validateForm() {
			if (!this.formData.description.trim()) {
				uni.showToast({
					title: '请填写需求描述',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.formData.quantity || this.formData.quantity <= 0) {
				uni.showToast({
					title: '请填写正确的需求数量',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.formData.quantityUnit.trim()) {
				uni.showToast({
					title: '请填写数量单位',
					icon: 'none'
				});
				return false;
			}
			
			return true;
		},
		
		// 提交表单
		async onSubmit() {
			if (this.submitting) return;
			
			// 验证表单
			if (!this.validateForm()) {
				return;
			}
			
			// 检查登录状态
			if (!authStore.isLoggedIn()) {
				this.checkAuth();
				return;
			}
			
			this.submitting = true;
			
			try {
				// 构建提交数据
				const submitData = {
					description: this.formData.description.trim(),
					quantity: this.formData.quantity,
					quantityUnit: this.formData.quantityUnit.trim()
				};
				
				// 添加可选字段
				if (this.formData.contactName.trim()) {
					submitData.contactName = this.formData.contactName.trim();
				}
				if (this.formData.contactPhone.trim()) {
					submitData.contactPhone = this.formData.contactPhone.trim();
				}
				if (this.formData.image1) {
					submitData.image1 = this.formData.image1;
				}
				if (this.formData.image2) {
					submitData.image2 = this.formData.image2;
				}
				if (this.formData.image3) {
					submitData.image3 = this.formData.image3;
				}
				
				// 调用接口
				await api.post('/api/demand/create', submitData, true);
				
				uni.showToast({
					title: '发布成功',
					icon: 'success'
				});
				
				// 清空表单
				this.resetForm();
				
				// 1秒后跳转到我的需求页面
				setTimeout(() => {
					uni.navigateTo({ url: '/pages/demand/mine' });
				}, 1000);
				
			} catch (error) {
				console.error('发布需求失败:', error);
			} finally {
				this.submitting = false;
			}
		},
		
		// 重置表单
		resetForm() {
			this.formData = {
				description: '',
				quantity: '',
				quantityUnit: '',
				contactName: '',
				contactPhone: '',
				image1: '',
				image2: '',
				image3: ''
			};
			this.imageList = [];
		}
	}
}
</script>

<style scoped>
.form-textarea {
	border: 2rpx solid #e1e1e1;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
	width: 100%;
	box-sizing: border-box;
	min-height: 200rpx;
	resize: none;
}

.quantity-row {
	display: flex;
	gap: 20rpx;
}

.quantity-input {
	flex: 2;
	border: 2rpx solid #e1e1e1;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
}

.unit-input {
	flex: 1;
	border: 2rpx solid #e1e1e1;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
}

.image-upload {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.image-item {
	position: relative;
	width: 160rpx;
	height: 160rpx;
}

.uploaded-image {
	width: 100%;
	height: 100%;
	border-radius: 8rpx;
}

.delete-btn {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	width: 40rpx;
	height: 40rpx;
	background-color: #ff3b30;
	color: white;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
}

.upload-btn {
	width: 160rpx;
	height: 160rpx;
	border: 2rpx dashed #ccc;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f8f8f8;
}

.upload-text {
	font-size: 60rpx;
	color: #ccc;
}

.btn-group {
	margin-top: 60rpx;
	padding: 0 20rpx;
}

.submit-btn {
	width: 100%;
	padding: 30rpx 0;
	font-size: 32rpx;
}
</style>